<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="clearfix">
              <span>基础信息</span>
            </div>
          </template>
          <div class="info">
            <div class="info-image" @click="toggleFileInputStatus()">
              <input ref="fileInput" accept="image/*" @change="onUploadCover" type="file" hidden/>
              <img alt="" :src="userInfo.headImg"/>
              <span class="info-edit">
                                <i class="el-icon-lx-camerafill"></i>
                            </span>
            </div>
            <div class="info-name">
              <i class="el-icon-phone text-light font18"></i>
              {{ userInfo.phone }}
            </div>
            <div class="info-desc">
              <i class="el-icon-coin text-light font18"></i>
              ￥{{ userInfo.balance || 0 }}
              <el-button size="mini" round type="primary" @click="toggleChargeModal(true)" plain>充值</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="clearfix">
              <span>账户编辑</span>
            </div>
          </template>
          <el-form label-width="90px">
            <el-form-item label="昵称：">
              <el-input v-model="formData.name" placeholder="请填写昵称"></el-input>
            </el-form-item>
            <el-form-item label="邮箱：">
              <el-input v-model="formData.email" placeholder="请填写邮箱"></el-input>
            </el-form-item>
            <el-form-item label="身份证号：">
              <el-input v-model="formData.idNumber" placeholder="请填写身份证号"></el-input>
            </el-form-item>
            <el-form-item label="性别：">
              <el-radio-group v-model="formData.sex">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="新密码：">
              <el-input type="password" v-model="formData.password" placeholder="填写新密码保存后可修改"></el-input>
            </el-form-item>
            <el-form-item label="确认密码：">
              <el-input type="password" v-model="formData.rePassword" placeholder="填写新密码保存后可修改"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">保存</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>


    <!--充值 start-->
    <el-dialog
        v-model="chargeFormData.show"
        title="余额充值"
        width="50%">
      <el-form :model="chargeFormData" label-width="120px">
        <el-form-item label="充值金额(元)">
          <el-input-number v-model="chargeFormData.price" placeholder="充值金额"></el-input-number>
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input type="textarea" v-model="chargeFormData.remarks" placeholder="备注说明"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleChargeModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onCharge()">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <!--充值 end-->

  </div>
</template>

<script>
import {computed, reactive, ref, toRaw, watch} from "vue";
import {useStore} from "vuex";
import Member from "../api/modules/Member";
import {deepClone, isEmpty} from "../utils/helpers";
import Toast from "../utils/Toast";
import Media from "../api/modules/Media";
import Events from "../events/Events";

export default {
  name: "user",
  setup() {
    const store = useStore();
    const formData = ref({
      name: "",
      email: "",
      headImg: "",
      idNumber: "",
      sex: "",
      password: "",
      rePassword: "",
    });
    const fileInput = ref(null);
    const _formData = deepClone(toRaw(formData.value));
    const chargeFormData = reactive({
      show: false,
      type: 1, // 1：充值
      price: '',
      remarks: '',
    });

    // 充值
    function toggleChargeModal(show) {
      if (!show) {
        chargeFormData.type = 1;
        chargeFormData.price = '';
        chargeFormData.remarks = '';

      }
      chargeFormData.show = show;
    }

    const userInfo = computed(() => store.state.user.userInfo);
    watch(() => store.state.user.userInfo, (data) => {
      formData.value = Object.assign({}, _formData, data);
      formData.value.password = '';
    }, {
      immediate: true
    })

    async function onSubmit() {
      const _data = deepClone(toRaw(formData.value));

      if (isEmpty(_data.name)) {
        Toast.warning('昵称必须填写');
        return;
      }
      const emailReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z]{2,5}$/;
      if (!emailReg.test(_data.email)) {
        Toast.warning('请填写正确的邮箱地址');
        return;
      }
      const params = {
        id: _data.id,
        name: _data.name,
        email: _data.email,
        idNumber: _data.idNumber,
        sex: _data.sex,
      }
      if (!isEmpty(_data.password)) {
        if (_data.password !== _data.rePassword) {
          Toast.warning('两次输入的密码不相同');
          return;
        }
        params.password = _data.password;
      }
      try {
        const {message} = await Member.update(params);
        Toast.success(message);
        window.emitter.emit(Events.refreshUserInfo); // 刷新用户信息
      } catch (e) {
        Toast.warning(e.message);
      }
    }


    const toggleFileInputStatus = (val = true) => {
      if (!fileInput.value) {
        return
      }
      if (val) { // 选择文件
        fileInput.value.click();
      } else { // 重置选中的文件
        fileInput.value.value = '';
      }
    };

    function onUploadCover(e) {
      const file = e.target.files[0];
      Media.upload(file).then(async ({data}) => {
        toggleFileInputStatus(false)
        if (!data || !data.url) {
          Toast.warning('图片上传异常');
          return;
        }
        try {
          const params = {
            id: userInfo.value.id,
            headImg: data.url,

            name: userInfo.value.name,
            email: userInfo.value.email,
            idNumber: userInfo.value.idNumber,
            sex: userInfo.value.sex,
          }
          await Member.update(params);
          Toast.success('充值成功');
          window.emitter.emit(Events.refreshUserInfo); // 刷新用户信息
        } catch (e) {
          Toast.warning(e.message);
        }
      }).catch(e => {
        toggleFileInputStatus(false)
        Toast.warning(e.message || '上传失败')
      })

    }

    async function onCharge() {
      const price = Math.abs(Number(chargeFormData.price) || 0)
      if (price === 0) {
        Toast.error("充值金额必须大于0")
        return
      }
      try {
        const {message} = await Member.charge({
          price,
          userId: userInfo.value.id,
          remarks: chargeFormData.remarks,
        });
        Toast.success(message);
        toggleChargeModal(false)
        window.emitter.emit(Events.refreshUserInfo); // 刷新用户信息
      } catch (e) {
        Toast.error(e.message);
      }
    }

    return {
      onCharge,
      fileInput,
      chargeFormData,
      toggleChargeModal,
      formData,
      userInfo,
      onSubmit,
      onUploadCover,
      toggleFileInputStatus,
    };
  },
};
</script>

<style scoped>
.info {
  text-align: center;
  padding: 35px 0;
}

.info-image {
  position: relative;
  margin: auto;
  width: 100px;
  height: 100px;
  background: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 50px;
  overflow: hidden;
}

.info-image img {
  width: 100%;
  height: 100%;
}

.info-edit {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.info-edit i {
  color: #eee;
  font-size: 25px;
}

.info-image:hover .info-edit {
  opacity: 1;
}

.info-name {
  margin: 15px 0 10px;
  font-size: 24px;
  font-weight: 500;
  color: #262626;
}

.crop-demo-btn {
  position: relative;
}

.crop-input {
  position: absolute;
  width: 100px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
</style>
